﻿using System;
using System.Collections.Generic;

namespace Cms.Domain
{
    public class SourceCode : ICloneable, IComparable<SourceCode>
    {
        private SourceCodeVersion _currentVersion;
        private Site _site;
        private IList<SourceCodeVersion> _versions;

        public SourceCode()
        {
            _versions = new List<SourceCodeVersion>();
        }

        private SourceCode(SourceCode original)
            : this()
        {
            _site = original.Site;
            if (original.CurrentVersion == null)
                return;
            _currentVersion = (SourceCodeVersion)original.CurrentVersion.Clone();
            _versions.Add(_currentVersion);
            _currentVersion.Parent = this;
        }
        
        public virtual int ID { get; set; }

        public virtual Site Site
        {
            get { return _site; }
            set { _site = value; }
        }
        
        public virtual SourceCodeVersion CurrentVersion
        {
            get { return _currentVersion; }
            set { _currentVersion = value; }
        }

        public virtual IList<SourceCodeVersion> Versions
        {
            get { return _versions; }
            set { _versions = value; }
        }

        #region ICloneable Members

        public virtual object Clone()
        {
            return new SourceCode(this);
        }

        #endregion

        public virtual void AddVersion(string code, Administrator editedBy)
        {
            var scv = new SourceCodeVersion
                          {
                              Code = code,
                              EditedBy = editedBy,
                              Timestamp = DateTime.Now.Ticks.ToString(),
                              Parent = this
                          };
            _versions.Add(scv);
            _currentVersion = scv;
        }

        public virtual int CompareTo(SourceCode other)
        {
            return this.ID > 0 && this.ID == other.ID ? 0 : 1;
        }
    }
}